package com.demo.zhihu.service;

import javax.inject.Singleton;

import com.demo.zhihu.data.QuestionDao;
import com.demo.zhihu.data.UserDao;
import com.demo.zhihu.model.Answer;
import com.demo.zhihu.model.Comment;
import com.demo.zhihu.model.Like;
import com.demo.zhihu.model.Question;
import com.demo.zhihu.model.User;

import cn.techarts.dragonfly.app.AbstractService;
import cn.techarts.dragonfly.data.trans.Transactional;
@Singleton
public class QuestionServiceImpl extends AbstractService implements QuestionService {

	@Override
	@Transactional
	public Question ask(int asker, String tilte, String summary) {
		// TODO Auto-generated method stub
		var dao = getMapper(QuestionDao.class);
		dao.askQuestion(new Question(asker, tilte, summary));
		var userDao = this.getMapper(UserDao.class);
		userDao.setUserQuestions(new User(asker,1,0));
		return new Question(asker, tilte, summary);
	}

	@Override
	public Answer answer(int question, int user, String content) {
		// TODO Auto-generated method stub
		var param = new Answer(question, user, content);
        var dao = this.getMapper(QuestionDao.class);
        if(dao.doesUserAnswered(param) != 0) return null;
        dao.answerQuestion(param);
        dao.setQuestionAnswers(new Question(question, 1));
        var userDao = this.getMapper(UserDao.class);
        userDao.setUserAnswers(new User(user, 0, 1));
        return param;
	}
			
		@Override
		@Transactional
		public Comment reply(int comment, int commenter, String content) {
			var param = new Comment(Comment.ME, comment, commenter, content);
			var dao = getMapper(QuestionDao.class);
			dao.postComment(param);
			return param;
		}

		@Override
		@Transactional
		public Comment comment(int answer, int commenter, String content) {
			var param = new Comment(Answer.ME, answer, commenter, content);
			var dao = getMapper(QuestionDao.class);
			dao.postComment(param);
			dao.setAnswerComments(new Answer(answer, 1));
			return param;
		}
	
		@Override
		@Transactional
		public boolean likeSomeone(int type, int id, int user) {
		    var param = new Like(user, type, id);
		    var dao = getMapper(QuestionDao.class);
		    if(dao.didUserLikeSomeone(param) == 0) {
		        param.setCanceled(false);
		        dao.likeSomeone(param);
		    } else {
		        param.setCanceled(true);
		        dao.dislikeSomeone(param);
		    }
		    if(type == Answer.ME) {
		        dao.setAnswerLikes(param);
		        param.setUser(dao.getAnswerer(id));
		        dao.setUserLikes(param);
		    } else {
		        dao.setCommentLikes(param);
		    }
		    return true;
		}
}
